<template>
	<div class="system-role-container">
		<el-dialog title="修改角色" v-model="isShowDialog" >
			<el-form ref="editRoleFormRef" :model="formData" :rules="formRules" label-width="80px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="角色名称" prop="roleName">
							<el-input v-model="formData.roleName" placeholder="请输入角色名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="权限字符" prop="roleKey">
							<el-input v-model="formData.roleKey" placeholder="请输入角色权限字符" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="角色状态" prop="status">
							<el-select v-model="formData.status" placeholder="请选择角色状态" clearable class="w100">
								<el-option label="正常" value="0"></el-option>
								<el-option label="停用" value="1"></el-option>
								<el-option label="删除" value="2"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="角色排序" prop="orderNum">
							<el-input-number v-model="formData.orderNum" :min="0" :max="999" clearable class="w100"></el-input-number>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="菜单权限">
							<el-cascader
								placeholder="请选择菜单权限（可选填）"
								v-model="formData.menuIds"
								:options="menus"
								:props="{expandTrigger: 'hover', multiple: true, value: 'id', label: 'menuName', children: 'children' }"
								collapse-tags
								class="w100"
								clearable>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
						<el-form-item label="数据权限" prop="dataScope">
							<el-select v-model="formData.dataScope" placeholder="请选择数据权限" clearable class="w100">
								<el-option label="全部数据权限" value="1"></el-option>
								<el-option label="自定义数据权限" value="2"></el-option>
								<el-option label="本部门数据权限" value="3"></el-option>
								<el-option label="本部门及以下数据权限" value="4"></el-option>
								<el-option label="仅本用户数据权限" value="5"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="数据范围">
							<el-cascader
								placeholder="请选择数据范围（可选填）"
								v-model="formData.deptIds"
								:disabled="formData.dataScope != 2"
								:options="depts"
								:props="{expandTrigger: 'hover', multiple: true, value: 'id', label: 'deptName', children: 'children' }"
								collapse-tags
								class="w100"
								clearable>
							</el-cascader>
						</el-form-item>
					</el-col>
					<el-col>
						<el-form-item label="备注">
							<el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">取 消</el-button>
					<el-button type="primary" @click="onSubmit" :disabled="formData.roleKey == 'SysAdmin'">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { editRole, getRole } from '/@/api/system/role/index';
import { getMenuList } from '/@/api/system/menu/index';
import { getDeptList } from '/@/api/system/dept/index';
import { verifyStringCode } from '/@/utils/toolsValidate';
import { lineToTreeData } from '/@/utils/commonFunction';
export default {
	name: 'role/edit',
	setup(props, context) {
		const editRoleFormRef = ref();
		const validRoleKey = (rule, value, callback) => {
			if(!value){
				return callback(new Error('权限字符不能为空'));
			}
			if(!verifyStringCode(value)){
				return callback(new Error('只允许字母或数字或下划线组成5~16个字符'));
			}
			callback();
		}

		const state = reactive({
			isShowDialog: false,
			menus: [],
			depts: [],
			formData: {
				dataScope: '',
				menuIds: [],
				deptIds: []
			},
			formRules : {
				status: { required: true, message: '角色状态不能为空', trigger: 'change' },
				roleName: { required: true, message: '角色名称不能为空', trigger: 'blur' },
				roleKey: { required: true, validator: validRoleKey, trigger: 'blur' },
				dataScope: { required: true, message: '数据权限不能为空', trigger: 'change' },
				orderNum: { required: true, message: '角色排序不能为空', trigger: 'blur' }
			}
		});
		//初始化菜单级联
		const loadMenus = async () => {
			await getMenuList({isCommon: 'N'}).then((res) => {
				if(res.code == 0){
					state.menus = lineToTreeData(res.data);
				}
			});
		}
		//初始化部门级联
		const loadDepts = async () => {
			await getDeptList().then((res) => {
				if(res.code == 0){
					state.depts = lineToTreeData(res.data);
				}
			});
		}
		//获取角色
		const loadRole = async (id: string) => {
			await getRole({'id' : id}).then((res) => {
				if(res.code == 0){
					state.formData.menuIds = res.data.menuIds;
					state.formData.deptIds = res.data.deptIds;
				}
			});
		}
		// 打开弹窗
		const openDialog = (row: any) => {
			state.isShowDialog = true;
			if(row){
				state.formData = Object.assign({}, row);
			}
			loadRole(row.id);
			loadMenus();
			loadDepts();
		};
		// 关闭弹窗
		const closeDialog = (row?: object) => {
			state.isShowDialog = false;
			for(var key in state.formData) {
				state.formData[key] = undefined;
			}
			editRoleFormRef.value.resetFields();
		};
		// 取消
		const onCancel = () => {
			closeDialog();
		};
		// 保存
		const onSubmit = () => {
			editRoleFormRef.value.validate(valid => {
				if(valid){
					let menuIds = [],deptIds = [];
					state.formData.menuIds.forEach(items => {
						if(typeof items == 'string'){
							menuIds.push(items);
						}else{
							items.forEach(item => {
								menuIds.push(item);
							});
						}
					});
					menuIds = Array.from(new Set(menuIds));//去重

					state.formData.deptIds.forEach(items => {
						if(typeof items == 'string'){
							deptIds.push(items);
						}else{
							items.forEach(item => {
								deptIds.push(item);
							});
						}
					});
					deptIds = Array.from(new Set(deptIds));//去重

					let params = {
						id: state.formData.id,
						status: state.formData.status,
						roleName: state.formData.roleName,
						roleKey: state.formData.roleKey,
						orderNum: state.formData.orderNum,
						menuIds: menuIds,
						dataScope: state.formData.dataScope,
						deptIds: deptIds,
						remark: state.formData.remark
					}
					editRole(params).then((res) => {
						if(res.code === 0){
							ElMessage.success('保存成功');
							context.emit('submit');
							closeDialog(); // 关闭弹窗
						}
					});
				}
			});
		};
		
		return {
			editRoleFormRef,
			openDialog,
			closeDialog,
			onCancel,
			onSubmit,
			...toRefs(state),
		};
	},
};
</script>
